<?php
/**
 * TinyCatPHP 极简、快速、创新、易用、高性能的PHP应用开发框架
 * User: CnTaiGe <hst042@163.com>
 * Date: 2017/11/17
 */

namespace TinyCatPHP\libs\utils;

use TinyCatPHP\exception\SysException;
use TinyCatPHP\libs\config\Config;

class ParseTemp
{
    protected $pathFile;
    protected $tmpData;

    public function __construct($pathFile, $tmpData)
    {
        $this->pathFile = $pathFile . Config::get('template_suffix');
        if (!file_exists($this->pathFile)) {
            throw new SysException('找不到模板文件: ' . $this->pathFile);
        }
        $this->tmpData = $tmpData;
    }

    /**
     * 解析模板变量
     * @return string
     */
    public function parse()
    {
        $saveFile = Config::get('data_path') . '/cache/template/' . md5($this->pathFile) . '.php';
        if (!Config::get('debug') && file_exists($saveFile)) {
            return $saveFile;
        }
        $contents = preg_replace_callback('/!?\$\w\S*?#|!?:\w\S*?#/S', function ($arr) {
            if (strpos($arr[0], '!') === 0) {
                return rtrim(ltrim($arr[0], '!'), '#');
            }
            if (strpos($arr[0], ':') === 0) {
                $parseL = $this->parseTag($arr[0]);
                if ($parseL !== false)
                    return $parseL;
            }
            return '<?php echo (' . rtrim($arr[0], '#') . ');?>';
        }, File::read($this->pathFile));
        if (count(Config::get('template_replace')) !== 0) {
            //替换字符
            $tempReplace = Config::get('template_replace');
            foreach ($tempReplace as $kk => $kv) {
                $contents = str_replace($kk, $kv, $contents);
            }
        }
        $file = File::save($saveFile, $contents, false);
        return $file;
    }

    protected function parseTag($tag)
    {
        $_var = rtrim(ltrim($tag, ':'), '#');
        switch (true) {
            case  (strpos($_var, ')') !== false):
                return '<?php echo (' . $_var . ');?>';
                break;
            default:
                return '<?php echo (' . $_var . '());?>';
        }
    }
}